<?php
Class  Model3 
{
	public $db = '';
	private $field = '';
	private $page = '';
	
	public function __construct()
	{
		$this->dbinit();
	}
	
	public function dbinit()
	{
	   	static $_db;
	   	if(empty($_db))
	   	{
			$this->db = $_db= new mysqlDB(C('db_host'), C('db_user'), C('db_pass'), C('db_name'));
	   	}
	   	else 
	   	{
	  	 	$this->db = $_db;
	   	}	
	}
	
	/**
	 * 获取配置信息
	 * @param string $key
	 * @return multitype:unknown
	 */
	public function getCfg($key = '')
	{
		if($key)
		{
			$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='".$key."'";
			$arr = $this->getOne($sql);
		}
		else
		{
			$sql = "SELECT op_value,op_key FROM ".$this->table('options')." WHERE op_key='wap_support' ";
			$arr = array();
			$res = $this->getAll($sql);
			if(count($res) > 0)
			{
				foreach($res as $k => $v)
				{
					$arr[$v['op_key']] = $v['op_value'];
				}
			}
		}
		C($arr);
		return $arr;
	}
	
	/**
	 * 获取并保存access_token
	 * @return 
	 */
	public function getAccessToken()
	{
		$path = ROOT_PATH."/Qiaqia/Json/access_token.json";
		$data = json_decode(file_get_contents($path), true);
		if(empty($data['access_token']) || $data['expire_time'] < yf_time())
		{
			$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' order by id asc";
			$temp = $this->getCol($sql);
			$app['appid'] = $temp[0];
			$app['appsecret'] = $temp[1];
			$new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
			$info['access_token'] = $new_info['access_token'];
			$info['expire_time'] = yf_time() + 7000;
 			$fp = fopen($path, "w");
 			fwrite($fp, json_encode($info));
 			fclose($fp);
			return $new_info['access_token'];
		}
		else 
		{
			Ctrl("weixin")->setToken($data['access_token']);
			return $data['access_token'];
		}
// 		$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='access_token' OR op_key='token_life' OR op_key='appid' OR op_key='appsecret' order by id asc";
// 		$temp = $this->getCol($sql);
// 		$app['appid'] = $temp[0];
// 		$app['appsecret'] = $temp[1];
// 		$wx_token['access_token'] = $temp[2];
// 		$wx_token['token_life'] = $temp[3];
// 		if($wx_token['access_token'] == '' || $_SERVER['REQUEST_TIME'] > $wx_token['token_life'])//7200
// 		{
// 	        $new_info = Ctrl("weixin")->getToken($app['appid'], $app['appsecret']);
	     	
// 	        $sql = "UPDATE ".$this->table('options')." SET op_value='".$new_info['access_token']."' WHERE op_key='access_token'";
// 	       	$res = $this->db->query($sql);
// 	       	$time = $_SERVER['REQUEST_TIME']+$new_info['expires_in']-800;
// 	       	$sql = "UPDATE ".$this->table('options')." SET op_value='".$time."' WHERE op_key='token_life'";
// 	       	$res2 = $this->db->query($sql);
// 	       	return $new_info['access_token'];
// 		}
// 		else 
// 		{
// 			Ctrl("weixin")->setToken($wx_token['access_token']);
// 		   	return $wx_token['access_token'];
// 		}
	}
	
	public function del($cfg = array())
	{
		$t=$cfg['table'];
		unset($cfg['table']);
		$where=" WHERE 1=1 AND ";
		$logic=" AND ";
		foreach($cfg as $k=>$v)
		{
		   if(is_array($v))
			{
				$where.="".$k." in (".implode(',',$v).")".$logic;
			}
			else 
			{
			     $where.=" ".$k."='".$v."'".$logic;
			}
		}
		
		$where=$where."1=1";
		
		
		$sql="DELETE FROM ".$this->table($t).$where;
		$res=$this->query($sql);
		
		return $res;
	}
	public function update($info,$cfg)
	{
		if(is_array($cfg['id']))
		{
			foreach($cfg['id'] as $k=>$v)
			{
				$where='';
				foreach($info[$k] as $kk=>$vv)
				{
				
					$where.=" $kk='$vv',";
				}
				
				$where=substr($where,0,strlen($where)-1);
				
				$sql="UPDATE ".$this->table($cfg['table'])." SET ".$where." WHERE id='".$v."'";
				
				 $res=$this->query($sql);
			}
			return true;
		}
		else
		{
		
			foreach($info as $k=>$v)
			{
		
				$where.=" $k='$v',";
			}
				
			$where=substr($where,0,strlen($where)-1);
		
			$sql="UPDATE ".$this->table($cfg['table'])." SET ".$where." WHERE id='".$cfg['id']."'";
				
			return $res=$this->query($sql);
		}
	}
	
	public function db_count($cfg=array())
	{
		$where='';
		foreach($cfg as $k=>$v)
		{
		  if($k!='table')
		  {
		  	if(is_array($v))
		  	{
		  		if(current($v)!='')
		  		{
		  		$where.=" $k in (".implode(',',$v).") AND";
		  		}
		  	}
		  	else 
		  	{
			    $where.=" $k='$v' AND";
		  	}
		  }
		
		}
		$where=substr($where,0,strlen($where)-3);
		$sql=' SELECT count(1) FROM '.$this->table($cfg['table'])." WHERE ".$where;
		$num=$this->getOne($sql);
		if($num)
		{
			return $num;
		}
		else 
		{
			return 0;
		}
	}
	
	public function insert($info,$table)
	{
		$_value='';
		foreach($info as $k=>$v)
		{
			if(is_array($v))
			{
				$field='';
				$value='';
				foreach($v as $kk=>$vv)
				{
					$field.="$kk,";
					
					
					$value.="'$vv',";
				}
				$_field=substr($field,0,strlen($field)-1);
				$value=substr($value,0,strlen($value)-1);
				$_value.="(".$value."),";
			}
			else
			{
				$field.="$k,";
		
		
				$value.="'$v',";
					
			}
			
		}
			
			
		$field=substr($field,0,strlen($field)-1);
		$value=substr($value,0,strlen($value)-1);
			if($_value!='')
			{
				$_value=substr($_value,0,strlen($_value)-1);
			   $sql="INSERT INTO ".$this->table($table)." (".$_field.") VALUES ".$_value."";	
			}
			else 
			{
		       $sql="INSERT INTO ".$this->table($table)." (".$field.") VALUES(".$value.")";
			}
			
		if(!$res=$this->query($sql))
		{
			return false;
		}
		else 
		{
			if($id = $this->insert_id())
			{
				return $id;
			}
			else 
			{
				return true;
			}
			
		}
	}
	
	public function insert_id()
	{
		return $this->db->insert_id();
	}
	
	public function query($sql)
	{
		return $this->db->query($sql);
	}
	
	public function create_link($page_count,$curpage=1)
	{
		return $this->db->create_link($page_count,$curpage);
	}
	
	public function getpagelink()
	{
		return $this->db->page_link;
	}
	
	public function show_page($sql,$page=1,$page_size=10,$cfg=array(),$count_sql='')
	{
		$count_sql = $count_sql == '' ? 'SELECT count(*) ' : $count_sql;
		$from_index = strpos($sql,'FROM');
		$c_sql = $count_sql.substr($sql, $from_index);
		$data = array();
		$num = $this->db->getOne($c_sql);
		if($num > 0)
		{
			if(strtolower(GROUP_NAME) == 'home')
			{
				$cfg['rewrite'] = REWRITE;
			}
			
			$page = new Page($page,$num,$page_size,$cfg);
			if(strtolower(GROUP_NAME) == 'home' && DEFAULT_LANG == 'en_us')
			{
				$page->set_lang(array('first_page' => 'First', 'next_page' => 'Next', 'pre_page' => 'Pre', 'last_page' => 'Last',));
			}
			
			$page->create_arr();
			$sql = $sql.' LIMIT '.$page->select_from.$page->select_limit;
			$data['result'] = $this->db->getAll($sql);
			$data['page'] = $page->html_page();
		}
		return $data;
	}
	
	public function get_page($field,$from,$where='',$page=1,$page_size='10')
	{
		return $this->db->get_page($field,$from,$where,$page,$page_size);
	}
	
	public function table($table_name)
	{
		$table=C('prefix').$table_name;
		return $table ;
	}
	
	public function getOne($sql)
	{
		$result=$this->db->getOne($sql);
		return $result;
	}
	
	public function getAll($sql)
	{
		$result=$this->db->getAll($sql);
		return $result;
	}
	
	public function getCol($sql)
	{
		$result=$this->db->getCol($sql);
		return $result;
	}
	
	public function getRow($sql)
	{
		$result=$this->db->getRow($sql);
		return $result;
	}
	
	/**
	 * 获取jsdk的参数
	 * @author yf
	 */
	public function get_jsdk()
	{
// 		$access_token = $this->getAccessToken();
// 		$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid' OR op_key='appsecret' OR op_key='jsapi_ticket' OR op_key='jsapi_time'";
// 		$temp = $this->getCol($sql);
// 		$app['appid'] = $temp[0];
// 		$app['appsecret'] = $temp[1];
// 		$wx_token['jsapi_ticket'] = $temp[2];
// 		$wx_token['jsapi_time'] = $temp[3];
		
// 		if($wx_token['jsapi_ticket'] == '' || $_SERVER['REQUEST_TIME'] > $wx_token['jsapi_time'])//7200
// 		{
// 			$new_info = Ctrl("weixin")->getJsapiTicket($access_token);
// 			if(empty($new_info['ticket']))
// 			{
// 				$sql = "UPDATE ".$this->table('options')." SET op_value='' WHERE op_key='access_token'";
// 				$this->query($sql);
// 				unset($new_info);
// 				$access_token = $this->getAccessToken();
// 				$new_info = Ctrl("weixin")->getJsapiTicket($access_token);
// 			}
//  			$sql = "UPDATE ".$this->table('options')." SET op_value='".$new_info['ticket']."' WHERE op_key='jsapi_ticket'";
//  			$res = $this->db->query($sql);
//  			$time = $_SERVER['REQUEST_TIME']+$new_info['expires_in']-800;
//  			$sql = "UPDATE ".$this->table('options')." SET op_value='".$time."' WHERE op_key='jsapi_time'";
//  			$res2 = $this->db->query($sql);
//  			$jsapi_ticket = $new_info['ticket'];
// 		}
// 		else
// 		{
// 			$jsapi_ticket = $wx_token['jsapi_ticket'];
// 		}

		$sql = "SELECT op_value FROM ".$this->table('options')." WHERE op_key='appid'";
		$appid = $this->getOne($sql);
		
		$path = ROOT_PATH."/Qiaqia/Json/jsapi_ticket.json";
		$data = json_decode(file_get_contents($path), true);
		
		if(empty($data['jsapi_ticket']) || $data['expire_time'] < yf_time())
		{
			$access_token = $this->getAccessToken();
			$new_info = Ctrl("weixin")->getJsapiTicket($access_token);
			$info['jsapi_ticket'] = $new_info['ticket'];
			$info['expire_time'] = yf_time() + 7000;
			$fp = fopen($path, "w");
			fwrite($fp, json_encode($info));
			fclose($fp);
			$jsapi_ticket = $new_info['ticket'];
		}
		else 
		{
			$jsapi_ticket = $data['jsapi_ticket'];
		}
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = yf_time();
		$nonceStr = $this->createNonceStr();
		
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		
		$signature = sha1($string);
		
		$signPackage = array(
				"appId"     => $appid,
				"nonceStr"  => $nonceStr,
				"timestamp" => $timestamp,
				"url"       => $url,
				"signature" => $signature,
				"rawString" => $string
		);
		return $signPackage;
	}
	
	/**
	 * jsdk获取字段
	 * @param number $length
	 * @return string
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	/**
	 * 写入数据库(导入excel)
	 * @param unknown $table
	 * @param unknown $table_name
	 * @param unknown $data
	 */
	public function entry_forms($table, $table_name, $data)
	{
		$sql = "insert into ".$this->table($table_name)." (".$table.") values (".$data.")";
		return $this->query($sql);
	}
	
}